package com.wgke.bluetooth.ui;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.newmobiler.android.ui.adapter.CellAdapter;
import com.newmobiler.android.ui.adapter.cell.MultiCell;
import com.wgke.bluetooth.R;
import com.wgke.bluetooth.db.CmdEntity;
import com.wgke.bluetooth.event.EventReadBean;
import com.wgke.bluetooth.event.EventWriteBean;
import com.wgke.bluetooth.tools.BtMsg;
import com.wgke.bluetooth.utils.SpUtil;
import com.wgke.bluetooth.utils.ToastUtil;
import com.wgke.bluetooth.vm.ReadWriteVM;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class ReadWriteActivity extends BaseActivity<ReadWriteVM> {
    @Override
    public int layoutId() {
        return R.layout.actvity_read_write;
    }

    @Override
    protected void initStateBar() {
        super.initStateBar();
        String title = getIntent().getStringExtra("title");
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle(title);
        toolbar.setNavigationOnClickListener(v -> finish());
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initView() {
        String uuid = getIntent().getStringExtra("uuid");
        View rlRead = findViewById(R.id.rlRead);
        TextView readTitle = rlRead.findViewById(R.id.inputTitle);
        Button readBtn1 = rlRead.findViewById(R.id.inputBtn1);
        Button readBtn2 = rlRead.findViewById(R.id.inputBtn2);
        Button noticeBtn = rlRead.findViewById(R.id.inputBtn3);
        EditText readInput = rlRead.findViewById(R.id.input);


        View rlWrite = findViewById(R.id.rlWrite);
        TextView writeTitle = rlWrite.findViewById(R.id.inputTitle);
        Button writeBtn1 = rlWrite.findViewById(R.id.inputBtn1);
        Button writeBtn2 = rlWrite.findViewById(R.id.inputBtn2);
        Button crcBtn = rlWrite.findViewById(R.id.inputBtn3);
        EditText writeInput = rlWrite.findViewById(R.id.input);
        RecyclerView rv = rlWrite.findViewById(R.id.rv);

        readTitle.setText("READ/NOTIFY 服务");
        readBtn1.setText("清理");
        readBtn2.setText("读取");
        readBtn1.setOnClickListener(v -> vm.content.postValue(""));
        readBtn2.setOnClickListener(v -> readByService(uuid));

        writeTitle.setText("WRITE 服务");
        writeBtn1.setText("清理");
        writeBtn2.setText("指令");
        writeBtn1.setOnClickListener(v -> writeInput.setText(""));
        writeBtn2.setOnClickListener(v -> {
            newCmd = "";
            writeByService(writeInput.getText().toString());
        });

        noticeBtn.setText("通知");
        noticeBtn.setVisibility(View.VISIBLE);
        noticeBtn.setOnClickListener(v -> {
            String text = noticeBtn.getText().toString();
            vm.setNotice(TextUtils.equals("通知", text));
            noticeBtn.setText((TextUtils.equals("通知", text) ? "取消" : "") + "通知");
        });

        crcBtn.setText("crc");
        crcBtn.setVisibility(View.VISIBLE);
        crcBtn.setOnClickListener(v -> {
            String result = vm.changeCrc(writeInput.getText().toString().replace(" ", ""));
            if (!TextUtils.isEmpty(result)) {
                writeInput.setText(result);
            } else {
                ToastUtil.showLongMsg("CRC变更失败");
            }
        });

        vm.content.observe(this, readInput::setText);

        vm.list.observe(this, cmdEntities -> setCmdList(cmdEntities, rv, writeInput));
        vm.loadCmdList();

        //ToastUtil.showLongMsg("请先尝试读取，读取会初始化 特征数据！！");
        postDelayed(500, () -> readByService(uuid));
        postDelayed(2000, () -> {
            vm.setNotice(true);
            ToastUtil.showLongMsg("正在开启通知管理");
            noticeBtn.setText("清理通知");
        });
    }

    public void setCmdList(List<CmdEntity> cmdList, RecyclerView rv, EditText writeInput) {
        Log.e("ReadWriteActivity", "setCmdList: " + cmdList.size());

        CellAdapter adapter = new CellAdapter(this);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3, GridLayoutManager.HORIZONTAL, false);
        rv.setLayoutManager(layoutManager);
        rv.setAdapter(adapter);

        adapter.setDataList(MultiCell.convert2(R.layout.item_cmd_btn, cmdList, (h, c) -> {
            h.setText(R.id.btnCmd, c.name);
            h.getView(R.id.btnCmd).setOnClickListener(v -> setEditCmd(writeInput,c));
            h.getView(R.id.btnCmd).setOnTouchListener((v, event) -> {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    newCmd = "" + c.cmd;
                    Log.e("ReadWriteActivity", "MotionEvent.ACTION_DOWN");
                    sendLongCmd(v, c.cmd);
                } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    Log.e("ReadWriteActivity", "MotionEvent.ACTION_UP");
                    newCmd = "";
                }
                return false;
            });
        }));
        if (!cmdList.isEmpty() && SpUtil.getUseParse()) {
            View v = findViewById(R.id.rlRead);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) v.getLayoutParams();
            params.weight = 2f;  // 修改weight值
            v.setLayoutParams(params);
        }
    }

    void setEditCmd(EditText input,CmdEntity bean){
        input.setText(vm.changeCmd(bean.cmd));
    }

    void showLongNotice(View v, String msg) {
        // 创建"+1"文本视图
        TextView plusOne = new TextView(this);
        plusOne.setTextSize(16);
        plusOne.setTextColor(Color.RED);
        // 添加到父容器中
        ViewGroup rootView = (ViewGroup) v.getRootView();
        rootView.addView(plusOne);
        plusOne.setText(msg);

        // 设置初始位置
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        plusOne.setX(location[0] + v.getWidth() / 2f - plusOne.getWidth() / 2f);
        plusOne.setY(location[1] - plusOne.getHeight());

        // 执行动画
        plusOne.animate().translationY(plusOne.getY() - 100).alpha(0).setDuration(1000).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                ViewGroup rootView = (ViewGroup) v.getRootView();
                rootView.removeView(plusOne);
            }
        }).start();
    }

    void notifySendMsg(View v, int count) {
        runOnUiThread(() -> {
            if (v != null && v.isAttachedToWindow()) {
                showLongNotice(v, "+" + count);
            }
        });
    }


    private String newCmd = "";

    private void sendLongCmd(View v, String cmd) {
        new Thread(() -> {
            try {
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int count = 0;
            while (!TextUtils.isEmpty(newCmd) && TextUtils.equals(newCmd, cmd)) {
                writeByService(cmd);
                notifySendMsg(v, count++);
                try {
                    Thread.sleep(150L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    public void readByService(String serviceUUID) {
        vm.readByService(serviceUUID);
    }

    public void writeByService(String data) {
        if (TextUtils.isEmpty(data) || data.trim().isEmpty()) {
            ToastUtil.showLongMsg("请输入数据");
            return;
        }
        byte[] bytes = BtMsg.hexStringToByteArray(data);
        if (bytes == null) {
            ToastUtil.showLongMsg("数据非法，HEX格式！！！");
            return;
        }
        vm.writeBytes(bytes);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageReadEvent(EventReadBean event) {
        vm.readBytes(event.isRead, event.bytes);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageWriteEvent(EventWriteBean event) {
        if (TextUtils.isEmpty(newCmd))
            ToastUtil.showLongMsg(event.success ? "写入成功！" : "错误" + event.msg);
    }

    @Override
    protected void onPause() {
        super.onPause();
        newCmd = "";
    }

    @Override
    protected void onStop() {
        super.onStop();
        vm.setNotice(false);
    }
}
